package controllers

import (
	"my-go-project/config"
	"my-go-project/model"
	"my-go-project/utils/token"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type UserList struct {
	PassageArea  *string `json:"PassageArea,omitempty"`
	PassageID    int64   `json:"PassageID"`
	PassagePic   string  `json:"PassagePic"`
	PassageTitle string  `json:"PassageTitle"`
	PassageType  string  `json:"PassageType"`
	IfLiked      bool    `json:"IfLiked"`
}

type UserListResponse struct {
	ProfilePhoto string     `json:"ProfilePhoto"`
	UName        string     `json:"UName"`
	UserID       int64      `json:"UserID"`
	PassageList  []UserList `json:"PassageList"`
}

type SquareList struct {
	AuthorID     int64   `json:"AuthorID"`
	PassageArea  *string `json:"PassageArea,omitempty"`
	PassageID    int64   `json:"PassageID"`
	PassagePic   string  `json:"PassagePic"`
	PassageType  string  `json:"PassageType"`
	PassageTitle string  `json:"PassageTitle"`
	ProfilePhoto string  `json:"ProfilePhoto"`
	UName        string  `json:"UName"`
	IfLiked      bool    `json:"IfLiked"`
}

type SquareListResponse struct {
	// 文章列表
	PassageList []SquareList `json:"PassageList"`
}

func GetUserPassage(ctx *gin.Context) {
	passageResponse := SquareListResponse{}
	passageList := []SquareList{}

	id, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "获取用户id失败!",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	userList, err := model.GetFocusList(id)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	userMessage, err := model.GetUserMessage(id)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	for _, user := range userList {
		ifLiked, err := model.IfLiked(int(user.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := SquareList{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     user.AuthorID,
			PassageArea:  user.PassageArea,
			PassageID:    user.PassageID,
			PassagePic:   user.PassagePic,
			PassageType:  user.PassageType,
			PassageTitle: user.PassageTitle,
			IfLiked:      ifLiked,
		}
		passageList = append(passageList, passage)
	}
	for i := range passageList {
		p := &passageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}
	passageResponse.PassageList = passageList

	ctx.JSON(http.StatusOK, passageResponse)
}

func GetFocusPassage(ctx *gin.Context) {
	passageResponse := SquareListResponse{}
	passageList := []SquareList{}

	// id, err := strconv.Atoi(ctx.Param("id"))
	// if err != nil {
	// 	ctx.JSON(http.StatusBadRequest, gin.H{
	// 		"error": err.Error(),
	// 	})
	// 	return
	// }

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	focusIDList, err := model.GetFocusIDList(int(uid))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	for _, f := range focusIDList {
		focusList, err := model.GetFocusList(f.FocusID)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, ff := range focusList {
			userMessage, err := model.GetUserMessage(int(ff.AuthorID))
			if err != nil {
				ctx.JSON(http.StatusInternalServerError, gin.H{
					"error": err.Error(),
				})
				return
			}
			ifLiked, err := model.IfLiked(int(ff.PassageID), int(uid))
			if err != nil {
				ctx.JSON(http.StatusInternalServerError, gin.H{
					"error": err.Error(),
				})
				return
			}
			passage := SquareList{
				ProfilePhoto: userMessage.ProfilePhoto,
				UName:        userMessage.UName,
				AuthorID:     ff.AuthorID,
				PassageArea:  ff.PassageArea,
				PassageID:    ff.PassageID,
				PassagePic:   ff.PassagePic,
				PassageType:  ff.PassageType,
				PassageTitle: ff.PassageTitle,
				IfLiked:      ifLiked,
			}
			passageList = append(passageList, passage)
		}
	}

	for i := range passageList {
		p := &passageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}
	passageResponse.PassageList = passageList
	ctx.JSON(http.StatusOK, passageResponse)
}

func GetSquarePassage(ctx *gin.Context) {
	passageResponse := SquareListResponse{}
	passageList := []SquareList{}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	squareList, err := model.GetSquareList()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	for _, square := range squareList {
		userMessage, err := model.GetUserMessage(int(square.AuthorID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		ifLiked, err := model.IfLiked(int(square.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := SquareList{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     square.AuthorID,
			PassageArea:  square.PassageArea,
			PassageID:    square.PassageID,
			PassagePic:   square.PassagePic,
			PassageType:  square.PassageType,
			PassageTitle: square.PassageTitle,
			IfLiked:      ifLiked,
		}
		passageList = append(passageList, passage)
	}
	for i := range passageList {
		p := &passageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}
	passageResponse.PassageList = passageList
	ctx.JSON(http.StatusOK, passageResponse)
}

func GetAdoptPassage(ctx *gin.Context) {
	passageResponse := SquareListResponse{}
	passageList := []SquareList{}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	adoptList, err := model.GetAdoptList()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	for _, adopt := range adoptList {
		userMessage, err := model.GetUserMessage(int(adopt.AuthorID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		ifLiked, err := model.IfLiked(int(adopt.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := SquareList{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     adopt.AuthorID,
			PassageArea:  adopt.PassageArea,
			PassageID:    adopt.PassageID,
			PassagePic:   adopt.PassagePic,
			PassageType:  adopt.PassageType,
			PassageTitle: adopt.PassageTitle,
			IfLiked:      ifLiked,
		}
		passageList = append(passageList, passage)
	}
	for i := range passageList {
		p := &passageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}
	passageResponse.PassageList = passageList
	ctx.JSON(http.StatusOK, passageResponse)
}
